// pages/core/discover/discover.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'recommend',
    currentFilter: 'all',
    priceOrder: 'desc',
    items: [],
    products: [],
    featuredItem: {},
    loading: false,
    refreshLoading: false,
    noMore: false,
    pageNo: 1,
    pageSize: 10,
    cartCount: 3
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.loadData(true);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时可以根据需要刷新数据
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if (!this.data.noMore && !this.data.loading) {
      this.loadMore();
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 加载数据
  loadData(reset = false) {
    if (this.data.loading) return;
    
    const pageNo = reset ? 1 : this.data.pageNo;
    
    this.setData({
      loading: true,
      noMore: false
    });
    
    if (reset) {
      this.setData({
        items: [],
        pageNo: 1
      });
    }
    
    // 如果是推荐标签，加载推荐数据
    if (this.data.activeTab === 'recommend') {
      this.loadRecommendData();
      return;
    }
    
    // 此处预留接口调用 - 获取列表数据
    const getListData = () => {
      // 未来实现: 调用云函数获取列表数据
      // 目前使用模拟数据
      return new Promise((resolve) => {
        setTimeout(() => {
          let list = [];
          
          if (this.data.activeTab === 'scenic') {
            list = [
              {
                id: 1,
                title: '黄果树瀑布',
                imageUrl: '/assets/images/discover/scenic1.jpg',
                tags: ['5A景区', '自然风光'],
                rating: 4.9,
                price: 180,
                address: '贵州省安顺市镇宁布依族苗族自治县'
              },
              {
                id: 2,
                title: '西江千户苗寨',
                imageUrl: '/assets/images/discover/scenic2.jpg',
                tags: ['民族风情', '历史文化'],
                rating: 4.8,
                price: 100,
                address: '贵州省黔东南苗族侗族自治州雷山县'
              },
              {
                id: 3,
                title: '梵净山',
                imageUrl: '/assets/images/discover/scenic3.jpg',
                tags: ['世界遗产', '自然风光'],
                rating: 4.7,
                price: 120,
                address: '贵州省铜仁市江口县、印江县'
              },
              {
                id: 4,
                title: '青岩古镇',
                imageUrl: '/assets/images/discover/scenic4.jpg',
                tags: ['历史古迹', '文化遗产'],
                rating: 4.6,
                price: 80,
                address: '贵州省贵阳市花溪区'
              },
              {
                id: 5,
                title: '织金洞',
                imageUrl: '/assets/images/discover/scenic5.jpg',
                tags: ['溶洞奇观', '自然风光'],
                rating: 4.5,
                price: 110,
                address: '贵州省毕节市织金县'
              }
            ];
          } else if (this.data.activeTab === 'activity') {
            list = [
              {
                id: 101,
                title: '2025贵州民族文化节',
                imageUrl: '/assets/images/discover/activity1.jpg',
                timeRange: '2025-05-15 至 2025-05-20',
                location: '贵阳市观山湖区',
                price: 99,
                status: '预售中'
              },
              {
                id: 102,
                title: '贵州茶文化体验活动',
                imageUrl: '/assets/images/discover/activity2.jpg',
                timeRange: '2025-05-25 至 2025-05-30',
                location: '贵阳市南明区',
                price: 129,
                status: '预售中'
              },
              {
                id: 103,
                title: '侗族大歌表演',
                imageUrl: '/assets/images/discover/activity3.jpg',
                timeRange: '2025-06-01 至 2025-06-05',
                location: '黔东南苗族侗族自治州黎平县',
                price: 88,
                status: '热卖中'
              },
              {
                id: 104,
                title: '苗族踩花山节',
                imageUrl: '/assets/images/discover/activity4.jpg',
                timeRange: '2025-06-10 至 2025-06-15',
                location: '黔东南苗族侗族自治州镇远县',
                price: 78,
                status: '即将开始'
              }
            ];
          } else if (this.data.activeTab === 'food' || this.data.activeTab === 'hotel' || this.data.activeTab === 'clothing' || this.data.activeTab === 'health') {
            // 其他标签的模拟数据
            list = [
              {
                id: 201,
                title: '示例项目1',
                imageUrl: '/assets/images/discover/placeholder.jpg',
                tags: ['标签1', '标签2'],
                rating: 4.5,
                price: 88,
                address: '贵州省贵阳市'
              },
              {
                id: 202,
                title: '示例项目2',
                imageUrl: '/assets/images/discover/placeholder.jpg',
                tags: ['标签1', '标签2'],
                rating: 4.6,
                price: 98,
                address: '贵州省贵阳市'
              }
            ];
          }
          
          // 应用筛选条件
          if (this.data.currentFilter === 'popular') {
            // 按照评分/人气排序
            list.sort((a, b) => {
              return (b.rating || 0) - (a.rating || 0);
            });
          } else if (this.data.currentFilter === 'price') {
            // 按照价格排序
            list.sort((a, b) => {
              return this.data.priceOrder === 'asc'
                ? a.price - b.price
                : b.price - a.price;
            });
          }
          
          // 模拟分页
          const startIndex = (pageNo - 1) * this.data.pageSize;
          const endIndex = startIndex + this.data.pageSize;
          const pagedList = list.slice(startIndex, endIndex);
          
          // 模拟没有更多数据
          const hasMore = startIndex + pagedList.length < list.length;
          
          resolve({
            code: 0,
            message: 'success',
            data: {
              list: pagedList,
              total: list.length,
              hasMore: hasMore
            }
          });
        }, 800);
      });
    };
    
    getListData()
      .then((res) => {
        if (res.code === 0) {
          const { list, hasMore } = res.data;
          
          this.setData({
            items: reset ? list : [...this.data.items, ...list],
            noMore: !hasMore,
            pageNo: pageNo + 1
          });
        } else {
          wx.showToast({
            title: res.message || '获取数据失败',
            icon: 'none'
          });
        }
      })
      .catch((error) => {
        console.error('获取列表数据失败:', error);
        wx.showToast({
          title: '获取数据失败，请重试',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({
          loading: false,
          refreshLoading: false
        });
      });
  },
  
  // 加载推荐数据
  loadRecommendData() {
    // 此处预留接口调用 - 获取推荐数据
    const getRecommendData = () => {
      // 未来实现: 调用云函数获取推荐数据
      // 目前使用模拟数据
      return new Promise((resolve) => {
        setTimeout(() => {
          const featuredItem = {
            id: 1001,
            title: '2025贵州旅游年卡',
            imageUrl: '/assets/images/discover/featured.jpg',
            price: 299,
            description: '一卡在手，畅游贵州100+景区，享受专属优惠与服务',
            tags: ['超值', '热门'],
            rating: 4.9,
            reviewCount: 1280
          };
          
          const products = [
            {
              id: 2001,
              title: '贵州茅台酒',
              imageUrl: '/assets/images/discover/product1.jpg',
              price: 1499,
              origin: '贵州茅台',
              sales: '月销1000+',
              rating: 5.0,
              tags: ['名酒', '礼品']
            },
            {
              id: 2002,
              title: '贵州苗族银饰',
              imageUrl: '/assets/images/discover/product2.jpg',
              price: 299,
              origin: '黔东南',
              sales: '月销500+',
              rating: 4.8,
              tags: ['手工', '民族']
            },
            {
              id: 2003,
              title: '贵州辣椒酱',
              imageUrl: '/assets/images/discover/product3.jpg',
              price: 39.9,
              origin: '遵义',
              sales: '月销2000+',
              rating: 4.7,
              tags: ['美食', '特产']
            }
          ];
          
          resolve({
            code: 0,
            message: 'success',
            data: {
              featuredItem,
              products,
              hasMore: false
            }
          });
        }, 800);
      });
    };
    
    getRecommendData()
      .then((res) => {
        if (res.code === 0) {
          const { featuredItem, products, hasMore } = res.data;
          
          this.setData({
            featuredItem,
            products,
            noMore: !hasMore,
            pageNo: 2
          });
        } else {
          wx.showToast({
            title: res.message || '获取数据失败',
            icon: 'none'
          });
        }
      })
      .catch((error) => {
        console.error('获取推荐数据失败:', error);
        wx.showToast({
          title: '获取数据失败，请重试',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({
          loading: false,
          refreshLoading: false
        });
      });
  },
  
  // 加载更多
  loadMore() {
    this.loadData();
  },
  
  // 刷新
  onRefresh() {
    this.setData({
      refreshLoading: true
    });
    this.loadData(true);
  },
  
  // 搜索点击
  onSearchTap() {
    wx.navigateTo({
      url: '/pages/search/search'
    });
  },
  
  // 标签切换
  onTabChange(e) {
    const activeTab = e.currentTarget.dataset.tab;
    
    if (activeTab === this.data.activeTab) {
      return;
    }
    
    this.setData({
      activeTab,
      currentFilter: 'all'
    });
    
    this.loadData(true);
  },
  
  // 筛选点击
  onFilterTap(e) {
    const { filter, order } = e.currentTarget.dataset;
    
    if (filter === 'price') {
      // 价格筛选需要切换排序方向
      const priceOrder = this.data.currentFilter === 'price'
        ? (this.data.priceOrder === 'asc' ? 'desc' : 'asc')
        : 'desc';
      
      this.setData({
        currentFilter: filter,
        priceOrder
      });
    } else {
      this.setData({
        currentFilter: filter
      });
    }
    
    this.loadData(true);
  },
  
  // 项目点击
  onItemTap(e) {
    const { id, type } = e.currentTarget.dataset;
    let url = '';
    
    switch (type) {
      case 'scenic':
        url = `/pages/tourism/scenic_detail/scenic_detail?id=${id}`;
        break;
      case 'activity':
        url = `/pages/tourism/activity_detail/activity_detail?id=${id}`;
        break;
      case 'food':
        url = `/pages/tourism/food_detail/food_detail?id=${id}`;
        break;
      case 'hotel':
        url = `/pages/tourism/hotel_detail/hotel_detail?id=${id}`;
        break;
      case 'clothing':
        url = `/pages/shopping/product_detail/product_detail?id=${id}&type=clothing`;
        break;
      case 'health':
        url = `/pages/health/service_detail/service_detail?id=${id}`;
        break;
      case 'featured':
        url = `/pages/tourism/featured_detail/featured_detail?id=${id}`;
        break;
      case 'product':
        url = `/pages/shopping/product_detail/product_detail?id=${id}`;
        break;
      default:
        url = `/pages/common/detail/detail?id=${id}&type=${type || 'default'}`;
    }
    
    wx.navigateTo({
      url
    });
  },
  
  // 查看更多
  onMoreTap(e) {
    const { type } = e.currentTarget.dataset;
    
    wx.navigateTo({
      url: `/pages/discover/list/list?type=${type}`
    });
  },
  
  // 添加到购物车
  onAddToCart(e) {
    const { id, type } = e.currentTarget.dataset;
    
    wx.showToast({
      title: '已加入购物车',
      icon: 'success'
    });
    
    // 更新购物车数量
    this.setData({
      cartCount: this.data.cartCount + 1
    });
    
    // 此处预留接口调用 - 添加到购物车
  },
  
  // 立即购买
  onBuyNow(e) {
    const { id, type } = e.currentTarget.dataset;
    
    wx.navigateTo({
      url: `/pages/transaction/confirm_order/confirm_order?id=${id}&type=${type}`
    });
  },
  
  // 购物车点击
  onCartTap() {
    wx.navigateTo({
      url: '/pages/transaction/cart/cart'
    });
  }
})